package com.yawn.zddefect.util;

import org.activiti.engine.history.HistoricVariableInstance;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * activiti中使用得到的工具方法
 *
 * @author Created by yawn on 2018-01-10 16:32
 */
public class ActivitiUtil {

    private ActivitiUtil() {
    }

    /**
     * 将历史参数列表设置到实体中去
     *
     * @param entity          实体
     * @param varInstanceList 历史参数列表
     */
    public static <T> void setHistoricVars(T entity, List<HistoricVariableInstance> varInstanceList) {
        Class<?> tClass = entity.getClass();
        for (HistoricVariableInstance varInstance : varInstanceList) {
            try {
                Field field = tClass.getDeclaredField(varInstance.getVariableName());
                field.setAccessible(true);
                field.set(entity, varInstance.getValue());
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }


    public static <T> void setVars(T entity, Map<String, Object> variables) {
        Class<?> tClass = entity.getClass();
        try {
            for (Map.Entry<String, Object> entry : variables.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                Field field = tClass.getDeclaredField(key);
                if (field == null) {
                    continue;
                }
                field.setAccessible(true);
                field.set(entity, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
